import { useWorkFlowStore } from '@/store/workflowStore'
import { useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { getWorkFlowDetailApi } from './API'
import WorkflowPage from './flow'
import { knowledgeListUpdate } from './utils'

export default function WorkflowPageWrap() {
  const { flow, initFlow, destroyFlow } = useWorkFlowStore()
  
  const { id } = useParams()

  useEffect(() => {
    console.log('>>>load WorkflowPageWrap', flow, id)
    if (!flow || flow.id !== id) {
      getWorkFlowDetailApi(id).then(_flow => {
        console.log('>>>load WorkflowPageWrap', _flow)
        let flow = _flow.flow
        if (flow?.graph?.nodes?.length > 0) {
          const res = flow.graph.nodes.findIndex(
            node => node.data.type === 'qa_retriever' && node?.data?.knowledgeList?.length > 0
          )
          // 知识节点&&知识库列表存在=_flow.knowledge_list匹配更新的列表
          if (res !== -1 && _flow.knowledge_list.length > 0) {
            flow = knowledgeListUpdate(flow, _flow.knowledge_list)
          }
        }
        initFlow(flow, _flow.tool_list, _flow.knowledge_list)
      })
    }
    return () => destroyFlow() // 销毁reactFlow实例
  }, [])

  return <div className="flow-page-positioning">{flow && <WorkflowPage flow={flow} />}</div>
}
